package com.equipmentmanager;

import javax.swing.*;
import java.awt.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

// 用户类
class User {
    private String username;
    private String password;
    private boolean isAdmin;

    public User(String username, String password, boolean isAdmin) {
        this.username = username;
        this.password = password;
        this.isAdmin = isAdmin;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public boolean isAdmin() {
        return isAdmin;
    }
}

// 设备数据类
class EquipmentData {
    private double temperature;
    private double waterLevel;

    public EquipmentData(double temperature, double waterLevel) {
        this.temperature = temperature;
        this.waterLevel = waterLevel;
    }

    public double getTemperature() {
        return temperature;
    }

    public double getWaterLevel() {
        return waterLevel;
    }
}

// 数据库管理类（关键修改）
class DatabaseManager {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/equipment_db?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC";
    private static final String USER = "root";
    private static final String PASS = "a101798989";
    private static final String EQUIPMENT_TABLE = "equipment";
    private static final String USER_TABLE = "users";

    // 静态块加载驱动类
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL JDBC驱动加载成功");
        } catch (ClassNotFoundException e) {
            System.err.println("错误：找不到MySQL JDBC驱动！");
            System.err.println("请下载并添加mysql-connector-java-8.x.x.jar到您的类路径");
        }
    }

    // 初始化数据库 - 解决图片中的错误
    public void initDatabase() {
        // 先检查数据库连接是否可用
        try (Connection conn = DriverManager.getConnection(DB_URL, USER, PASS)) {
            System.out.println("数据库连接成功！");

            try (Statement stmt = conn.createStatement()) {
                // 创建设备表
                String createEquipmentTableSQL = "CREATE TABLE IF NOT EXISTS " + EQUIPMENT_TABLE + " (" +
                        "id INT PRIMARY KEY AUTO_INCREMENT," +
                        "name VARCHAR(50) NOT NULL," +
                        "temperature DOUBLE NOT NULL," +
                        "water_level DOUBLE NOT NULL," +
                        "record_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP" +
                        ")";
                stmt.executeUpdate(createEquipmentTableSQL);
                System.out.println("设备表创建/已存在");

                // 创建用户表
                String createUserTableSQL = "CREATE TABLE IF NOT EXISTS " + USER_TABLE + " (" +
                        "id INT PRIMARY KEY AUTO_INCREMENT," +
                        "username VARCHAR(50) NOT NULL UNIQUE," +
                        "password VARCHAR(50) NOT NULL," +
                        "is_admin BOOLEAN NOT NULL" +
                        ")";
                stmt.executeUpdate(createUserTableSQL);
                System.out.println("用户表创建/已存在");

                // 检查是否存在管理员账户，不存在则创建
                String checkAdminSQL = "SELECT COUNT(*) FROM " + USER_TABLE + " WHERE is_admin = true";
                ResultSet rs = stmt.executeQuery(checkAdminSQL);
                if (rs.next() && rs.getInt(1) == 0) {
                    String insertAdminSQL = "INSERT INTO " + USER_TABLE + " (username, password, is_admin) VALUES ('zjz', 'a101798989', true)";
                    stmt.executeUpdate(insertAdminSQL);
                    System.out.println("已创建默认管理员账户: zjz");
                }
            }

            System.out.println("数据库初始化完成");
        } catch (SQLException e) {
            // 解决图片中的错误提示
            String errorMessage = "数据库连接失败:\n\n" +
                    "1. 请检查MySQL服务是否运行\n" +
                    "2. 确保用户名/密码正确\n" +
                    "3. JDBC驱动是否加载\n\n" +
                    "当前配置:\n" +
                    "URL: " + DB_URL + "\n" +
                    "用户: " + USER + "\n" +
                    "密码: " + PASS;

            showDatabaseErrorDialog(errorMessage);

            throw new RuntimeException("数据库初始化失败", e);
        }
    }

    // 专门针对图片中的错误提示框
    private void showDatabaseErrorDialog(String message) {
        JOptionPane.showMessageDialog(
                null,
                message,
                "数据库错误",
                JOptionPane.ERROR_MESSAGE
        );
    }

    // 插入模拟数据
    public void insertMockData() {
        String[] equipmentNames = {"搅拌釜", "水槽", "储罐"};
        Random random = new Random();

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "INSERT INTO " + EQUIPMENT_TABLE + " (name, temperature, water_level) VALUES (?, ?, ?)")) {

            for (String name : equipmentNames) {
                for (int i = 0; i < 10; i++) {
                    pstmt.setString(1, name);
                    pstmt.setDouble(2, 20 + random.nextDouble() * 60); // 温度20-80℃
                    pstmt.setDouble(3, random.nextDouble() * 100); // 水位0-100%
                    pstmt.executeUpdate();
                }
            }
            System.out.println("模拟数据插入成功");
        } catch (SQLException e) {
            System.err.println("模拟数据插入失败: " + e.getMessage());
        }
    }

    // 获取最新设备数据
    public EquipmentData getLatestData(String equipmentName) {
        String sql = "SELECT temperature, water_level FROM " + EQUIPMENT_TABLE +
                " WHERE name = ? ORDER BY record_time DESC LIMIT 1";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, equipmentName);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new EquipmentData(
                            rs.getDouble("temperature"),
                            rs.getDouble("water_level")
                    );
                }
            }
        } catch (SQLException e) {
            System.err.println("查询设备数据失败: " + e.getMessage());
        }
        return new EquipmentData(0, 0);
    }

    // 用户登录验证
    public User validateUser(String username, String password) {
        String sql = "SELECT is_admin FROM " + USER_TABLE + " WHERE username = ? AND password = ?";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return new User(username, password, rs.getBoolean("is_admin"));
                }
            }
        } catch (SQLException e) {
            System.err.println("用户验证失败: " + e.getMessage());
        }
        return null;
    }

    // 用户注册
    public void registerUser(String username, String password) {
        String sql = "INSERT INTO " + USER_TABLE + " (username, password, is_admin) VALUES (?, ?, false)";

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.executeUpdate();
            System.out.println("用户注册成功: " + username);
        } catch (SQLException e) {
            System.err.println("用户注册失败: " + e.getMessage());
        }
    }

    // 获取所有设备名称
    public List<String> getAllEquipmentNames() {
        List<String> equipmentNames = new ArrayList<>();
        String sql = "SELECT DISTINCT name FROM " + EQUIPMENT_TABLE;

        try (Connection conn = getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                equipmentNames.add(rs.getString("name"));
            }
        } catch (SQLException e) {
            System.err.println("获取设备名称失败: " + e.getMessage());
        }
        return equipmentNames;
    }

    // 添加设备
    public void addEquipment(String equipmentName) {
        if (getAllEquipmentNames().size() >= 5) {
            throw new RuntimeException("设备数量已达上限(5个)");
        }

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "INSERT INTO " + EQUIPMENT_TABLE + " (name, temperature, water_level) VALUES (?, 0, 0)")) {
            pstmt.setString(1, equipmentName);
            pstmt.executeUpdate();
            System.out.println("设备添加成功: " + equipmentName);
        } catch (SQLException e) {
            throw new RuntimeException("设备添加失败: " + e.getMessage());
        }
    }

    // 删除设备
    public void deleteEquipment(String equipmentName) {
        // 不能删除初始设备
        if (equipmentName.equals("搅拌釜") || equipmentName.equals("水槽") || equipmentName.equals("储罐")) {
            throw new RuntimeException("不能删除系统初始设备!");
        }

        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(
                     "DELETE FROM " + EQUIPMENT_TABLE + " WHERE name = ?")) {
            pstmt.setString(1, equipmentName);
            int rows = pstmt.executeUpdate();
            if (rows == 0) {
                throw new RuntimeException("设备不存在: " + equipmentName);
            }
            System.out.println("设备删除成功: " + equipmentName);
        } catch (SQLException e) {
            throw new RuntimeException("设备删除失败: " + e.getMessage());
        }
    }

    // 获取数据库连接
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(DB_URL, USER, PASS);
    }
}

// Excel生成器类
class ExcelGenerator {
    private DatabaseManager databaseManager;

    public ExcelGenerator(DatabaseManager databaseManager) {
        this.databaseManager = databaseManager;
    }

    public void generateReport() {
        try (Connection conn = databaseManager.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM equipment ORDER BY name, record_time DESC")) {

            // 创建Excel工作簿
            org.apache.poi.ss.usermodel.Workbook workbook = new org.apache.poi.xssf.usermodel.XSSFWorkbook();
            org.apache.poi.ss.usermodel.Sheet sheet = workbook.createSheet("设备数据");

            // 创建表头
            org.apache.poi.ss.usermodel.Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("设备名称");
            headerRow.createCell(1).setCellValue("温度(℃)");
            headerRow.createCell(2).setCellValue("水位(%)");
            headerRow.createCell(3).setCellValue("记录时间");

            // 填充数据
            int rowNum = 1;
            while (rs.next()) {
                org.apache.poi.ss.usermodel.Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(rs.getString("name"));
                row.createCell(1).setCellValue(rs.getDouble("temperature"));
                row.createCell(2).setCellValue(rs.getDouble("water_level"));
                row.createCell(3).setCellValue(rs.getTimestamp("record_time").toString());
            }

            // 调整列宽
            for (int i = 0; i < 4; i++) {
                sheet.autoSizeColumn(i);
            }

            // 保存文件
            try (FileOutputStream fileOut = new FileOutputStream("设备数据报表.xlsx")) {
                workbook.write(fileOut);
            }

            JOptionPane.showMessageDialog(null, "Excel报表生成成功！", "成功", JOptionPane.INFORMATION_MESSAGE);
        } catch (SQLException | IOException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "报表生成失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}

// 设备面板类
class EquipmentPanel extends JPanel {
    private String equipmentName;
    private DatabaseManager databaseManager;
    private JLabel temperatureLabel;
    private JLabel waterLevelLabel;
    private Timer refreshTimer;

    public EquipmentPanel(String equipmentName, DatabaseManager databaseManager) {
        this.equipmentName = equipmentName;
        this.databaseManager = databaseManager;
        setLayout(new BorderLayout(10, 10));
        setBorder(BorderFactory.createTitledBorder(equipmentName));
        setBackground(new Color(245, 245, 245));
        setPreferredSize(new Dimension(300, 150));
        initComponents();
        startRefreshTimer();
    }

    private void initComponents() {
        JPanel infoPanel = new JPanel(new GridLayout(2, 2, 10, 10));
        infoPanel.setBackground(new Color(245, 245, 245));

        JLabel temperatureTitle = new JLabel("温度:");
        temperatureLabel = new JLabel("加载中...");
        JLabel waterLevelTitle = new JLabel("水位:");
        waterLevelLabel = new JLabel("加载中...");

        infoPanel.add(temperatureTitle);
        infoPanel.add(temperatureLabel);
        infoPanel.add(waterLevelTitle);
        infoPanel.add(waterLevelLabel);

        JButton refreshButton = new JButton("刷新数据");
        refreshButton.addActionListener(e -> refreshData());

        add(infoPanel, BorderLayout.CENTER);
        add(refreshButton, BorderLayout.SOUTH);
    }

    private void startRefreshTimer() {
        refreshTimer = new Timer(5000, e -> refreshData());
        refreshTimer.start();
    }

    public void refreshData() {
        EquipmentData data = databaseManager.getLatestData(equipmentName);
        temperatureLabel.setText(String.format("%.1f ℃", data.getTemperature()));
        waterLevelLabel.setText(String.format("%.1f %%", data.getWaterLevel()));
    }

    public String getEquipmentName() {
        return equipmentName;
    }
}

// 登录界面类
class LoginFrame extends JFrame {
    private DatabaseManager databaseManager;
    private MainFrame mainFrame;

    public LoginFrame(DatabaseManager databaseManager, MainFrame mainFrame) {
        this.databaseManager = databaseManager;
        this.mainFrame = mainFrame;
        initComponents();
    }

    private void initComponents() {
        setTitle("设备管理系统 - 登录");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 标题面板
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(new Color(240, 240, 240));
        JLabel titleLabel = new JLabel("设备管理系统");
        titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
        titlePanel.add(titleLabel);
        add(titlePanel, BorderLayout.NORTH);

        // 登录面板
        JPanel loginPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        loginPanel.setBorder(BorderFactory.createEmptyBorder(20, 40, 20, 40));

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("密码:");
        JPasswordField passwordField = new JPasswordField();

        loginPanel.add(usernameLabel);
        loginPanel.add(usernameField);
        loginPanel.add(passwordLabel);
        loginPanel.add(passwordField);

        add(loginPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton loginButton = new JButton("登录");
        JButton registerButton = new JButton("注册");

        loginButton.addActionListener(e -> {
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());

            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            User user = databaseManager.validateUser(username, password);
            if (user != null) {
                mainFrame.setUser(user);
                mainFrame.setVisible(true);
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "用户名或密码错误", "登录失败", JOptionPane.ERROR_MESSAGE);
            }
        });

        registerButton.addActionListener(e -> new RegisterFrame(databaseManager, this));

        buttonPanel.add(loginButton);
        buttonPanel.add(registerButton);
        add(buttonPanel, BorderLayout.SOUTH);

        setVisible(true);
    }
}

// 注册界面类
class RegisterFrame extends JFrame {
    private DatabaseManager databaseManager;
    private LoginFrame loginFrame;

    public RegisterFrame(DatabaseManager databaseManager, LoginFrame loginFrame) {
        this.databaseManager = databaseManager;
        this.loginFrame = loginFrame;
        initComponents();
    }

    private void initComponents() {
        setTitle("设备管理系统 - 注册");
        setSize(400, 250);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 标题面板
        JPanel titlePanel = new JPanel();
        titlePanel.setBackground(new Color(240, 240, 240));
        JLabel titleLabel = new JLabel("用户注册");
        titleLabel.setFont(new Font("宋体", Font.BOLD, 20));
        titlePanel.add(titleLabel);
        add(titlePanel, BorderLayout.NORTH);

        // 注册面板
        JPanel registerPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        registerPanel.setBorder(BorderFactory.createEmptyBorder(20, 40, 20, 40));

        JLabel usernameLabel = new JLabel("用户名:");
        JTextField usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("密码:");
        JPasswordField passwordField = new JPasswordField();
        JLabel confirmLabel = new JLabel("确认密码:");
        JPasswordField confirmField = new JPasswordField();

        registerPanel.add(usernameLabel);
        registerPanel.add(usernameField);
        registerPanel.add(passwordLabel);
        registerPanel.add(passwordField);
        registerPanel.add(confirmLabel);
        registerPanel.add(confirmField);

        add(registerPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel();
        JButton registerButton = new JButton("注册");
        JButton cancelButton = new JButton("取消");

        registerButton.addActionListener(e -> {
            String username = usernameField.getText();
            String password = new String(passwordField.getPassword());
            String confirmPassword = new String(confirmField.getPassword());

            if (username.isEmpty() || password.isEmpty()) {
                JOptionPane.showMessageDialog(this, "用户名和密码不能为空", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(this, "两次输入的密码不一致", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            try {
                databaseManager.registerUser(username, password);
                JOptionPane.showMessageDialog(this, "注册成功，请登录", "成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "注册失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> dispose());

        buttonPanel.add(registerButton);
        buttonPanel.add(cancelButton);
        add(buttonPanel, BorderLayout.SOUTH);

        setVisible(true);
    }
}

// 主界面类
class MainFrame extends JFrame {
    private DatabaseManager databaseManager;
    private User currentUser;
    private JPanel equipmentPanel;
    private int addedEquipmentCount = 0;

    public MainFrame(DatabaseManager databaseManager) {
        this.databaseManager = databaseManager;
        initComponents();
    }

    public void setUser(User user) {
        this.currentUser = user;
        setTitle("设备管理系统 - 当前用户: " + user.getUsername() + (user.isAdmin() ? " [管理员]" : ""));
        updateEquipmentPanel();
    }

    private void initComponents() {
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 设备面板
        equipmentPanel = new JPanel();
        equipmentPanel.setLayout(new BoxLayout(equipmentPanel, BoxLayout.Y_AXIS));
        equipmentPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        JScrollPane scrollPane = new JScrollPane(equipmentPanel);
        add(scrollPane, BorderLayout.CENTER);

        // 底部按钮面板
        JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 15));

        JButton exportButton = new JButton("导出Excel报表");
        JButton logoutButton = new JButton("退出登录");

        exportButton.addActionListener(e -> new ExcelGenerator(databaseManager).generateReport());
        logoutButton.addActionListener(e -> {
            int option = JOptionPane.showConfirmDialog(this, "确定要退出登录吗?", "确认退出", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                setVisible(false);
                new LoginFrame(databaseManager, this);
            }
        });

        bottomPanel.add(exportButton);
        bottomPanel.add(logoutButton);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private void updateEquipmentPanel() {
        equipmentPanel.removeAll();

        try {
            List<String> equipmentNames = databaseManager.getAllEquipmentNames();
            for (String name : equipmentNames) {
                EquipmentPanel panel = new EquipmentPanel(name, databaseManager);
                equipmentPanel.add(panel);
                equipmentPanel.add(Box.createVerticalStrut(20));
            }

            // 管理员功能
            if (currentUser != null && currentUser.isAdmin()) {
                JPanel adminPanel = new JPanel();
                JButton addButton = new JButton("添加设备");
                JButton deleteButton = new JButton("删除设备");

                addButton.addActionListener(e -> {
                    if (addedEquipmentCount >= 2) {
                        JOptionPane.showMessageDialog(this, "最多只能添加2个设备", "操作限制", JOptionPane.WARNING_MESSAGE);
                        return;
                    }

                    String name = JOptionPane.showInputDialog(this, "请输入设备名称:");
                    if (name != null && !name.trim().isEmpty()) {
                        try {
                            databaseManager.addEquipment(name);
                            EquipmentPanel panel = new EquipmentPanel(name, databaseManager);
                            equipmentPanel.add(panel);
                            equipmentPanel.add(Box.createVerticalStrut(20));
                            addedEquipmentCount++;
                            equipmentPanel.revalidate();
                            equipmentPanel.repaint();
                            JOptionPane.showMessageDialog(this, "设备添加成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                        } catch (Exception ex) {
                            JOptionPane.showMessageDialog(this, "设备添加失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });

                deleteButton.addActionListener(e -> {
                    if (addedEquipmentCount == 0) {
                        JOptionPane.showMessageDialog(this, "没有可删除的设备", "提示", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }

                    List<String> names = databaseManager.getAllEquipmentNames();
                    List<String> addedNames = new ArrayList<>();

                    for (String name : names) {
                        if (!name.equals("搅拌釜") && !name.equals("水槽") && !name.equals("储罐")) {
                            addedNames.add(name);
                        }
                    }

                    if (addedNames.isEmpty()) {
                        JOptionPane.showMessageDialog(this, "没有可删除的设备", "提示", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }

                    String[] nameArray = addedNames.toArray(new String[0]);
                    String selected = (String) JOptionPane.showInputDialog(this,
                            "请选择要删除的设备:",
                            "删除设备",
                            JOptionPane.QUESTION_MESSAGE,
                            null,
                            nameArray,
                            nameArray[0]);

                    if (selected != null) {
                        try {
                            databaseManager.deleteEquipment(selected);
                            for (Component comp : equipmentPanel.getComponents()) {
                                if (comp instanceof EquipmentPanel) {
                                    EquipmentPanel panel = (EquipmentPanel) comp;
                                    if (panel.getEquipmentName().equals(selected)) {
                                        equipmentPanel.remove(panel);
                                        equipmentPanel.remove(Box.createVerticalStrut(20));
                                        addedEquipmentCount--;
                                        break;
                                    }
                                }
                            }
                            equipmentPanel.revalidate();
                            equipmentPanel.repaint();
                            JOptionPane.showMessageDialog(this, "设备删除成功", "成功", JOptionPane.INFORMATION_MESSAGE);
                        } catch (Exception ex) {
                            JOptionPane.showMessageDialog(this, "设备删除失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                });

                adminPanel.add(addButton);
                adminPanel.add(deleteButton);
                add(adminPanel, BorderLayout.NORTH);
            }

            equipmentPanel.revalidate();
            equipmentPanel.repaint();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "加载设备信息失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}

// 主类（根据图片修改）
public class Equipment { // 类名改为Equipment以匹配图片
    public static void main(String[] args) {
        try {
            // 设置界面风格为系统风格
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            System.out.println("设置系统界面风格");

            // 创建数据库管理器
            DatabaseManager databaseManager = new DatabaseManager();

            // 初始化数据库（关键部分）
            databaseManager.initDatabase();

            // 插入模拟数据（仅第一次运行）
            if (databaseManager.getAllEquipmentNames().isEmpty()) {
                databaseManager.insertMockData();
            }

            // 创建主界面
            MainFrame mainFrame = new MainFrame(databaseManager);
            mainFrame.setVisible(false);  // 初始不显示

            // 显示登录界面
            new LoginFrame(databaseManager, mainFrame);

        } catch (Exception e) {
            e.printStackTrace();

            // 根据图片要求显示错误对话框
            String message = "数据库连接失败：\n\n" +
                    "1. 请检查MySQL服务是否运行\n" +
                    "2. 确保用户名/密码正确\n" +
                    "3. JDBC驱动是否加载\n\n" +
                    "错误详情: " + e.getMessage();

            JOptionPane.showMessageDialog(
                    null,
                    message,
                    "数据库错误",
                    JOptionPane.ERROR_MESSAGE
            );
        }
    }
}